#include "compu.h"

void SampleSpeed(void)
{
	unsigned int tem = 0;
	unsigned int st = 0;
	st = sumavsp / 200; // 控制电压ADC平均值

	if (st < NMINVD - 50) // ADC小于150则设置速度为0
		SetSpeed = 0;
	else if (st <= NMINVD) // 小于200则不响应
		;
	else if (st < NMAXVD) // 小于3525就响应
	{
		tem = MINSPEED + KKN * (st - NMINVD); // 最低200转速，根据电位器计算加速斜率，也就是把电位器的电压和最大最小速度建立函数关系
		SetSpeed = tem;
	}
	else
	{
		SetSpeed = MAXSPEED;
	}
}

double sumaa = 0, sumbb = 0, sumcc = 0;
void SampleOI(void)
{
	static unsigned char numcoua = 0, numcoub = 0, numcouc = 0;

	if (Motor_Start_F == 1)
	{
		sumaa += suma;
		numcoua++;
		if (numcoua >= 100)
		{
			sumia = sumaa / 100;
			numcoua = 0;
			sumaa = 0;
		}

		sumbb += sumb;
		numcoub++;
		if (numcoub >= 100)
		{
			sumib = sumbb / 100;
			numcoub = 0;
			sumbb = 0;
		}

		sumcc += sumc;
		numcouc++;
		if (numcouc >= 100)
		{
			sumic = sumcc / 100;
			numcouc = 0;
			sumcc = 0;
		}
	}

	else
	{
		numcoua = 0;
		sumaa = 0;
		sumia = 0;
		numcoub = 0;
		sumbb = 0;
		sumib = 0;
		numcouc = 0;
		sumcc = 0;
		sumic = 0;
	}
}

void SampleI(void)
{
	float td;
	float kt1 = 0;
	static unsigned char IErCount = 0;

	if (Motor_Start_F == 1)
	{
		kt1 = sumia;	 // 30次ADC采样的结果累加和
		td = kt1 * 0.41; // 1/4096*5000/5/0.02/30 5倍 20毫欧   //修正后的算法,前面为除，5为增益倍数，0.02为采样电阻大小。
		td = td * 0.001;
		td = td * OutPwmValue / 4.8; // 4.8是干啥的呢？
		CanshuIA = td;

		kt1 = sumib;
		td = kt1 * 0.41; // 1/4096*5000/5/0.02/30 5倍 20毫欧
		td = td * 0.001;
		td = td * OutPwmValue / 4.8;
		CanshuIB = td;

		kt1 = sumic;
		td = kt1 * 0.41; // 1/4096*5000/5/0.02/30 5倍 20毫欧
		td = td * 0.001;
		td = td * OutPwmValue / 4.8;
		CanshuIC = td;
	}
	else
	{
		CanshuIA = 0;
		CanshuIB = 0;
		CanshuIC = 0;
	}

	CanshuI = (CanshuIA + CanshuIB + CanshuIC) / 3;

	if (CanshuIC > 30000 || CanshuIB > 30000 || CanshuIA >= 30000)
		ErrorCode = 4;

	if (CanshuI >= ISH * 1000 && ErrorCode == 0)
	{
		IErCount++;
		if (IErCount >= NumErr)
		{
			ErrorCode = 4;
		}
	}
	else
		IErCount = 0;
}

void SampleV(void)
{
	float t;
	static unsigned char VErCount = 0, LVErCount = 0;
	unsigned int x;

	t = SampleData[4];						   // 母线电压
	t = t * 10 / 4096 * 5 / RV1 * (RV1 + RV2); //
	CanshuV = t;							   // CanshuV: 0.1V为单位*10
	if (CanshuV >= VSH * 10 && ErrorCode == 0) // 母线电压高于28V报警
	{
		VErCount++;
		if (VErCount >= NumErr)
		{
			ErrorCode = 6;
		}
	}
	else
		VErCount = 0;

	if (CanshuV <= LSH * 10 && ErrorCode == 0) // 小于10V也报警
	{
		LVErCount++;
		if (LVErCount >= NumErr)
		{
			ErrorCode = 8;
		}
	}
	else
		LVErCount = 0;
}
